﻿using System;
using System.IO;
using System.Xml;
using System.Web;
using System.Data.Common;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using SyCODE.Component;
using SyCODE.Component.Cryptography;
using SyCODE.Component.DataFactory;
using SyCODE.Component.Security;
using System.Web.Security;

namespace SyCODE.Blog.Topic
{
    /// <summary>
    /// PostTopic.aspx 的处理程序
    /// </summary>
    public class Post : HandlerBase
    {
        public override void ProcessRequest(HttpContext context)
        {
			Ticket ticket = Ticket.Get(FormsAuthentication.FormsCookieName);
            if (Ticket.Authenticate(ticket))
            {
                NameValueCollection nvc = new NameValueCollection(context.Request.Form);

                if (CheckInfo("syblog_topic_writeform", nvc))
                {
                    string bloger = ticket.Name;
                    nvc.Add("bloger", bloger);

                    string[] tags = FormatTags(nvc["tags"]);
                    nvc.Set("tags", String.Join(" ", tags));

                    DBAM dbam = new DBAM();
                    dbam.BuildParameters("posttopic", nvc);
                    try
                    {
                        dbam.Execute();
                        long id = (long)dbam.GetResult();
                        if (id > 0)
                        {
                            string title = nvc["title"];

                            string path = Path.Combine(AppPath.GetUserPhysicalPath(bloger), @"topic\" + id.ToString());
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }

                            XmlTextWriter writer = new XmlTextWriter(File.Create(path + @"\main.xml"), context.Response.ContentEncoding);

                            writer.WriteStartDocument();
                            writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='/ui/common/topic.xsl'");

                            writer.WriteStartElement("html");
                            writer.WriteAttributeString("nocomment", String.IsNullOrEmpty(nvc["nocomment"]) ? "0" : "1");
                            writer.WriteStartElement("head");

                            writer.WriteStartElement("meta");
                            writer.WriteAttributeString("http-equiv", "Content-Type");
                            writer.WriteAttributeString("content", "text/html; charset=" + context.Response.ContentEncoding.WebName);
                            writer.WriteEndElement();
                            writer.WriteStartElement("title");
                            writer.WriteString(title);
                            writer.WriteEndElement();

                            writer.WriteStartElement("meta");
                            writer.WriteAttributeString("id", id.ToString());
                            writer.WriteAttributeString("name", "author");
                            writer.WriteAttributeString("content", bloger);
                            writer.WriteEndElement();

                            writer.WriteStartElement("meta");
                            writer.WriteAttributeString("name", "keywords");
                            writer.WriteAttributeString("content", nvc["tags"].Replace(' ', ','));
                            writer.WriteEndElement();

                            writer.WriteStartElement("meta");
                            writer.WriteAttributeString("name", "description");
                            writer.WriteAttributeString("content", ParseNonPicSummary(nvc["summary"]));
                            writer.WriteEndElement();

                            writer.WriteStartElement("tags");
                            for (int i = 0; i < tags.Length; i++)
                            {
                                if (tags[i].Length > 0)
                                {
                                    writer.WriteStartElement("tag");
                                    writer.WriteAttributeString("word", tags[i]);
                                    writer.WriteAttributeString("code", HttpUtility.UrlEncode(tags[i]));
                                    writer.WriteEndElement();
                                }
                            }
                            writer.WriteEndElement();

                            writer.WriteEndElement();

                            writer.WriteStartElement("body");
                            writer.WriteCData(nvc["content"]);
                            writer.WriteEndElement();

                            writer.WriteEndElement();
                            writer.WriteEndDocument();
                            writer.Flush();
                            writer.Close();

                            if (nvc["public"] == "true")
                            {
                                SyCODE.SearchEngine.Simple.AddDocument(id.ToString(), bloger, HttpUtility.HtmlDecode(ticket.UserData), title, nvc["content"], nvc["tags"]);

                                try
                                {
                                    WriteStore(bloger);
                                }
                                catch
                                {
                                }

                                try
                                {
                                    WriteLast4(bloger, id.ToString(), title);
                                }
                                catch
                                {
                                }

                                if (nvc["quote"].Trim().StartsWith("http://", true, null))
                                {
                                    string url = context.Request.Url.Scheme + "://" + context.Request.Url.Host + (context.Request.Url.IsDefaultPort ? "" : ":" + context.Request.Url.Port.ToString()) + "/" + bloger + "/topic/" + id.ToString();

                                    TrackBack.Ping ping = new TrackBack.Ping(nvc["quote"].Trim(), url);

                                    ping.Title = nvc["title"];
                                    ping.BlogName = HttpUtility.HtmlDecode(ticket.UserData);
                                    ping.Excerpt = nvc["summary"];

                                    try
                                    {
                                        ping.Send();
                                    }
                                    catch (Exception ex)
                                    {
                                        Function.ClientAlert(StringResource.GetField("trackbackexception") + "\n\n" + ex.Message);
                                    }
                                }
                            }
                        }
                        else
                            Function.ClientAlert(StringResource.GetField("unkownexception"));
                    }
                    finally
                    {
                        dbam.Dispose();
                    }
                }
            }
            else
            {
                Function.ClientAlert(StringResource.GetField("authfaild"));
            }
        }
    }
}
